package com.ruoyi.system.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/30.
 */
public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    public static String postJson(String url,Map<String,Object> param){
        String content = null;
        try {
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            String paramStr = JSON.toJSONString(param);
            if(paramStr==null){
                paramStr = "";
            }
            StringEntity entity = new StringEntity(paramStr);
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            InputStream is = response.getEntity().getContent();
            content = IOUtils.toString(is,"utf-8");
            logger.info("接口返回内容："+content);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    public static String postWithJson(String url, Map<String,String> params, String json, Map<String,String> headers) {
        String returnValue = "这是默认返回值，接口调用失败";
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if(params != null){
                for(Map.Entry<String, String> param : params.entrySet()){
                    uriBuilder.addParameter(param.getKey(), param.getValue());
                }
            }
            returnValue = postWithJson(uriBuilder.build().toString(), json, headers);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnValue;
    }

    public static String postWithJson(String url, String json, Map<String,String> headers) {
        String returnValue = "这是默认返回值，接口调用失败";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();

            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(url);

            //第三步：给httpPost设置JSON格式的参数

            if(headers != null){
                for(Map.Entry<String, String> header : headers.entrySet()){
                    httpPost.addHeader(header.getKey(),header.getValue());
                }
            }
            if(StringUtils.isNotBlank(json)){
                StringEntity requestEntity = new StringEntity(json, "utf-8");
                requestEntity.setContentEncoding("UTF-8");
                httpPost.setEntity(requestEntity);
            }

            //第四步：发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost, responseHandler);

            logger.info("接口返回内容："+returnValue);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //第五步：处理返回值
        return returnValue;
    }

    public static String getWithJson(String url, Map<String,String> params, Map<String,String> headers) {
        String returnValue = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            //第一步：创建c对象
            httpClient = HttpClients.createDefault();

            //第二步：创建请求参数
            URIBuilder uriBuilder = new URIBuilder(url);
            if(params != null){
                for(Map.Entry<String, String> param : params.entrySet()){
                    uriBuilder.addParameter(param.getKey(), param.getValue());
                }
            }

            //第三步：创建httpGet对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            //第四步：给httpGet设置JSON格式的参数
            if(headers != null){
                for(Map.Entry<String, String> header : headers.entrySet()){
                    httpGet.addHeader(header.getKey(),header.getValue());
                }
            }

            //第四步：发送HttpPost请求，获取返回值
            HttpResponse response  = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if(response.getStatusLine().getStatusCode() == 200){
                returnValue = EntityUtils.toString(entity, "UTF-8");
            }
//            logger.info("接口返回内容："+returnValue);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //第五步：处理返回值
        return returnValue;
    }

    public static String doPost(String url, Map<String, String> param, String token) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            //httpPost.setHeader("token", token);
            httpPost.setHeader("Authorization","Basic "+token);
            httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static JSONObject HttpGet(String url) throws IOException {
        //实例化HttpClient接口
        CloseableHttpClient ch = HttpClients.createDefault();
        //实例化httpget 并传入参数
        HttpGet hget = new HttpGet(url);
        //执行请求
        CloseableHttpResponse rs = ch.execute(hget);
        //获取相应消息的实体
        HttpEntity entity = rs.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        JSONObject jsonObjectSearch = JSON.parseObject(result);
        ch.close();
        rs.close();
        return jsonObjectSearch;
    }

    public static Object postByHeader(String url, Map<String,String> customerHeader, Object dataMap, Object... params) {
        RestTemplate restTemplate = new RestTemplate();
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        setHeaders(headers, customerHeader);
        org.springframework.http.HttpEntity entity = new org.springframework.http.HttpEntity(dataMap, headers);

        String result  = restTemplate.postForEntity(url,  entity, String.class, params).getBody();
        return result;
    }

    /**
     *说明 : 设置自定义头
     * @param headers
     * @param customerHeaders
     * @return void
     */
    private static void setHeaders(HttpHeaders headers, Map<String, String> customerHeaders) {
        for(String key : customerHeaders.keySet()){
            headers.add(key, customerHeaders.get(key));
        }
    }

//    public static void main(String[] args) {
//        String url = "https://api.zhiwucloud.com/api/v1/structures/4575/factors";
//        Map<String,String> parameters = new HashMap<>();
//        parameters.put("display", StringUtils.EMPTY);
//        parameters.put("token","2ec5d98f-4a31-4fbc-bd36-3bc801619dbe");
//        Map<String,String> headers = new HashMap<>();
//        headers.put("Content-Type", "application/json");
//        System.out.println(getWithJson(url,parameters,headers));
//
//        //String url = "https://api.mp.usr.cn/usrCloud/user/login";
//        //JSONObject jo = new JSONObject();
//        //jo.put("account","sk5muaad");
//        //jo.put("password","edac7c5b3c7ef1d79748d39b3ff9b0c7");
//        //Map<String,String> headers = new HashMap<>();
//        //postWithJson(url,jo.toString(),headers);
//        //
//        //String url = "http://www.0531yun.cn/wsjc/app/QueryHistoryList";
//        //Map<String,String> headers = new HashMap();
//        //headers.put("userId","32793");
//        //Map<String,String> params = new HashMap();
//        //params.put("deviceKey","107239");
//        //params.put("nodeId","1");
//        //params.put("beginTime","2020-05-17 10:32:00");
//        //params.put("endTime","2020-05-17 11:02:00");
//        //params.put("isAlarmData","-1");
//        //getWithJson(url,params,headers);
//    }
}
